<?php
/**
 * alltosun.com  aliyun_sso_helper.php
 * ============================================================================
 * 版权所有 (C) 2009-2013 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 王德康 (wangdk@alltosun.com) $
 * $Date: 2016-1-6 下午2:28:05 $
 * $Id$
 */
require MODULE_PATH . '/aliysso/helper/aliyun-oss-php-sdk-master/autoload.php';

use OSS\OssClient;
use OSS\Core\OssException;

class aliysso_helper
{
    /**
     * 初始化sso对象
     */
    private static function get_SSOClient() {
        $accessKeyId = aliysso_config::OSS_ACCESS_ID;
        $accessKeySecret = aliysso_config::OSS_ACCESS_KEY;
        $endpoint = aliysso_config::OSS_ENDPOINT;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, true);
            return $ossClient;

        } catch (OssException $e) {
            print $e->getMessage();
        }

        return false;
    }

    /**
     * 返回完整的URL,注意CND的支持和缩略图的支持
     * @param unknown_type $image_name
     * @return boolean|string
     */
    public static function _image($image_name, $thumb = '') {
        $thumb_params = '';

        $thumbs = aliysso_config::$oss_thumbs;
        if (!$image_name) {
            return false;
        }
        if ($thumb) {
            if (isset($thumbs[$thumb])) {
                $thumb_params = $thumbs[$thumb];
            }
            $path = aliysso_config::OSS_CND_HOST . '/' . $image_name . '@' . $thumb_params;
        } else {
            $path = aliysso_config::OSS_CND_HOST . '/' . $image_name;
        }
        return $path;
    }

    /**
     * 从配置文件读取缩略图配置
     * @param mixed $res_type
     * @param $category_id 对应分类id
     * @return array
     * @author gaojj@alltosun.com
     */
    public static function get_res_thumb() {
        $res_thumb = aliysso_config::$oss_thumbs;
        if (!$res_thumb) {
            $res_thumb = array();
        }

        return $res_thumb;
    }


    /**
     * sso 上传图片
     * @param unknown_type $name 要生成的图片路径名称
     * @param unknown_type $path 要上传的图片路径，绝对路径
     * @return boolean
     */
    public static function sso_upload_file($name, $path) {
        $bucket = aliysso_config::OSS_BUCKET;
        $ossClient = self::get_SSOClient();

        $file_dir = date('Y/m/d/');
        if (!$ossClient->doesObjectExist($bucket, $file_dir)) {
            if (NULL != $ossClient->createObjectDir($bucket, $file_dir)) {
                return false;
            }
        }

        $object = $file_dir . uniqid() . $name;
        if ($ossClient->uploadFile($bucket, $object, $path) == NULL) {
            unlink($path);
            return $object;
        }
        return false;
    }

    /**
     * 上传文件
     * @param $file_info
     * @param $res_name 生成缩略图
     * @param $is_attachment 是否插入附件表
     *
     */
    public static function upload_file($file_info, $is_attachment = false, $res_name = '') {
        // php.ini限制的post大小
        $POST_MAX_SIZE = ini_get('post_max_size');
        $unit = strtoupper(substr($POST_MAX_SIZE, -1));
        $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

        if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier * (int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
            header("HTTP/1.1 500 Internal Server Error"); // This will trigger an uploadError event in SWFUpload
            throw new Exception('对不起，上传文件超过服务器限制大小。');
        }

        $allow_type = array_merge(Config::get('allow_image_type'), Config::get('allow_flash_type'));
        $upload_path = UPLOAD_PATH;

        // 上传验证
        $failed_msg = check_upload($file_info);
        if (!empty($failed_msg)) {
            throw new Exception($failed_msg);
        }

        // 扩展名
        $file = $file_info['name'];
        $ext_file_name = substr($file, -4);
        $new_file_name = uniqid() . $ext_file_name;

        // 阿里云上传
        $file_path = self::sso_upload_file($new_file_name, $file_info['tmp_name']);

        // 插入数据库
        $attachment_id = 0;

        if ($is_attachment) {

            // 附件类型
            $attachment_type = get_attachment_type($file_path);

            $attachment_info = array(
                'path' => $file_path,
                'user_id' => user_helper::get_user_id(),
                'type' => $attachment_type,
                'size' => $file_info['size'],
                'file_name' => htmlspecialchars($file_info['name'], ENT_NOQUOTES)
            );

            $attachment_id = _model('attachment')->create($attachment_info);

            if (empty($attachment_id)) {
                throw new Exception('数据库插入失败，请重试');
            }
        }

        return array('id' => $attachment_id, 'file_path' => $file_path);
    }

}